/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: YinJianFeng
 * @Date: 2024-03-29 10:15:27
 */
import { Box, Card, CardContent, InputBase, styled } from '@mui/material';
import React, { useEffect } from 'react';
import MaterialLibs from './MaterialLibs';
import { MaterialParams } from './types';
import { materialSetter } from './MaterialSetter';
import {
  CMEVENTS
} from '@amcax/base'
import {
  userEvents
} from '@app-cad/module';

const StyledLibraryBox = styled(Box)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'row',
  '.MuiButtonBase-root': {
    height: '25px',
  },
  '.MuiInputBase-root': {
    height: '25px',
    fontSize: '14px',
    paddingLeft: '5px',
    marginLeft: '3px',
    border: '1px solid ' + theme.palette.divider,
    borderRadius: '5px',
  },
}));

export default function MaterialLibrary({
  show,
  dxid,
  materials,
  faceIndex,
}: MaterialParams) {
  const materialRef = React.useRef(null);
  const [name, setName] = React.useState('');

  useEffect(() => {
    registerEvents();
    loadMaterials();
  }, []);

  const registerEvents = () => {
    userEvents.on(CMEVENTS.MATERIAL_SELECTED, (material: any) => {
      if (material) {
        materialRef.current = material;
        setName(material.name);
      }
    });
  };

  const loadMaterials = () => {
    // const materials = DataManager().getAllMaterials()
  };
  const updateMaterials = async () => {
    const material = materialRef.current;
    material['name'] = name;
    // await wsApi.editMaterials(material)
    materialSetter.editMaterial(material);
    userEvents.emit(CMEVENTS.MATERIAL_UPDATED, material);
  };

  return (
    <Card
      variant='outlined'
      sx={{ my: '10px' }}>
      <CardContent
        sx={{
          paddingTop: '10px',
          '&:last-child': {
            paddingBottom: '10px',
          },
        }}>
        {show ? (
          <StyledLibraryBox>
            <MaterialLibs
              dxid={dxid}
              materials={materials}
              faceIndex={faceIndex}
            />
            <InputBase
              sx={{ flex: 1 }}
              value={name}
              placeholder='请输入'
              onChange={(e) => {
                setName(e.target.value);
              }}
              onKeyUp={(e) => {
                if (e.key === 'Enter') {
                  updateMaterials();
                }
              }}
            />
          </StyledLibraryBox>
        ) : (
          <></>
        )}
      </CardContent>
    </Card>
  );
}
